using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using DatabaseUnitTesting.Utilities;
using DatabaseUnitTesting.Utilities.DataCompare;

namespace DatabaseUnitTesting
{
    public class DatabaseComparer
    {
        private readonly DataComparer _dataComparer;
        private SqlTransaction _transaction;
        private SqlConnection _connection;

        public DatabaseComparer(SqlConnection connection, string databaseOne, string databaseTwo)
        {
            _connection = connection;
            _dataComparer = new DataComparer(connection, databaseOne, databaseTwo);
        }

        public SqlTransaction BeginTestTransaction()
        {
            if (_transaction != null)
                EndTestTransaction();

            return (_transaction = _connection.BeginTransaction());
        }

        public void EndTestTransaction()
        {
            if (_transaction == null)
                throw new InvalidOperationException("Transaction does not exist");

            _dataComparer.CleanUp();
            _transaction.Rollback();
            _transaction.Dispose();
            _transaction = null;
        }

        public void WriteDiffsToXml(string filename)
        {
            XmlFileAdapter.Write(filename, _dataComparer.GenerateDifferences(_transaction));
        }

        public bool CompareDiffsToXml(string filename)
        {
            return XmlFileAdapter.Read(filename).Equals(_dataComparer.GenerateDifferences(_transaction));
        }

        public bool AreEqual()
        {
            return _dataComparer.GenerateDifferences(_transaction).TableCount == 0;
        }

        public virtual void AddObjectComparison(string schema1, string table1, string schema2, string table2)
        {
            _dataComparer.AddObjectComparison(schema1, table1, schema2, table2);
        }

        public void AddColumnToIgnore(string schema1, string name1, string columnName)
        {
            _dataComparer.AddColumnToIgnore(schema1, name1, columnName);
        }

        public void AddColumnsToIgnore(string schema1, string name1, List<string> columnNames)
        {
            _dataComparer.AddColumnsToIgnore(schema1, name1, columnNames);
        }

    }
}